<template>
  <initVanta 
    :color="vantaData.hexToNumber(selectedColor)" 
    :effect="selectedEffect"
    ref="vantaBg"
  />
  <div class="header">
    <button class="settings-btn" @click="openSettings">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
        <path d="M12 1l9.5 5.5v11L12 23l-9.5-5.5v-11L12 1zm0 2.311L4.5 7.653v8.694l7.5 4.342 7.5-4.342V7.653L12 3.311zM12 16a4 4 0 110-8 4 4 0 010 8zm0-2a2 2 0 100-4 2 2 0 000 4z"/>
      </svg>
    </button>
    <h1>Google Sheets Entry</h1>
  </div>
  <!-- 设置面板 -->
  <div v-if="showSettings" class="settings-panel">
    <h2>Google Sheets Settings</h2>
    <div v-for="(sheet, index) in sheetIds" :key="index" class="sheet-item">
      <input v-model="sheetIds[index]" placeholder="输入Sheet ID">
      <button @click="removeSheet(index)">删除</button>
    </div>
    <button class="add-sheet" @click="addSheet">+ Google Sheets ID</button>
    <div class="action-buttons">
      <button @click="saveSettings">Save</button>
      <button @click="closeSettings">Close</button>
    </div>
  </div>
  <div id="googleSheetsEntry">
    <div class="entry-form">
      <form>
        <div class = "form-columns">
          <div class = "column">
            <div class="container">
              <input type="text" name="text" v-model="plmCode" class="input" placeholder="PLM Code">
              <button class="search__btn" @click="searchCode">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="22" height="22">
                  <path d="M18.031 16.6168L22.3137 20.8995L20.8995 22.3137L16.6168 18.031C15.0769 19.263 13.124 20 11 20C6.032 20 2 15.968 2 11C2 6.032 6.032 2 11 2C15.968 2 20 6.032 20 11C20 13.124 19.263 15.0769 18.031 16.6168ZM16.0247 15.8748C17.2475 14.6146 18 12.8956 18 11C18 7.1325 14.8675 4 11 4C7.1325 4 4 7.1325 4 11C4 14.8675 7.1325 18 11 18C12.8956 18 14.6146 17.2475 15.8748 16.0247L16.0247 15.8748Z" fill="#efeff1"></path>
                </svg>
              </button>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.tcfType" required=false>
              <label>TCF type (Full/Partial)</label>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.sampleReceivedDate" required=false>
              <label> TCF review sample received date</label>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.reviewFromDate" required=false>
              <label>TCF review from date (received 1st report)</label>
            </div>
          </div>
          <div class = "column">
            <div class="container">
              <div id="search-results" v-if="searchResults">
                <p>{{ searchResults }}</p>
              </div>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.validateDate" required=false>
              <label>TCF validate date (all reports ok)</label>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.closeDate" required=false>
              <label>TCF CLOSE DATE</label>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.statusUpdate" required=false>
              <label>TCF status regular update</label>
            </div>
            <div class="user-box">
              <input type="text" name="" v-model="formData.closureStatus" required=false :class="{ 'red-text': formData.closureStatus.toLowerCase() === 'closed late' }">
              <label>TCF closure status</label>
            </div>
          </div>
        </div>
        <a href="#" @click.prevent="handleEntry">
          ENTRY
          <span></span>
        </a>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import initVanta from '../../../src/components/initVanta.vue';
import { ElMessage } from 'element-plus';
import { useVanta } from '../../../src/components/useVanta';

const { selectedColor, selectedEffect, hexToNumber } = useVanta();

const vantaData = useVanta();

declare const electronAPI: any;


// 数据及状态
const plmCode = ref('');
const searchResults = ref('');
const showSettings = ref(false);
const sheetIds = ref<string[]>([]);
const activeSheetId = ref(''); // 当前使用 Google Sheet ID
const activeSheet = ref(''); // 当前使用的Sheet
import { format } from 'date-fns';

// 初始化时从 localStorage 加载 Sheet ID
onMounted(() => {
  const savedSheetIds = localStorage.getItem('google-sheets-sheet-ids');
  if (savedSheetIds) {
    sheetIds.value = JSON.parse(savedSheetIds);
  }
});

// 添加formData定义
const formData = ref({
  tcfType: '',
  sampleReceivedDate: '',
  reviewFromDate: '',
  validateDate: '',
  closeDate: '',
  statusUpdate: '',
  closureStatus: ''
});

// 搜索逻辑
// P19-107-WRI-AUC13709
async function searchCode(event: Event) {
  event.preventDefault();
  if (plmCode.value.trim() === '') {
    ElMessage.error('Please enter PLM Code');
    return;
  }
  if (sheetIds.value.length === 0) {
    ElMessage.error('Please set Sheet ID first.');
    return;
  }

  // 显示搜索中提示
  const loadingMessage = ElMessage({
    message: 'Searching...',
    duration: 0,
    type: 'info',
    showClose: false
  });

  try {
    for (const sheetId of sheetIds.value) {
      if (sheetId.trim() !== '') {
        const sheetNames = await electronAPI.getSheetNames(sheetId);
        for (const sheet of sheetNames) {
          activeSheet.value = sheet;
          console.log('activeSheet:', sheet);
          // 获取整行数据
          const data = await electronAPI.readRowData(sheetId, `${sheet}!A1:Z1000`);
          const match = data.find((row: string[]) => row[5] === plmCode.value); // F列是索引5
          if (match) {
            activeSheetId.value = sheetId;
            // 填充表单数据
            formData.value = {
              tcfType: match[2] || '', // C列是索引2
              sampleReceivedDate: match[8] || '', // I列是索引8
              reviewFromDate: match[10] || '', // K列是索引10
              validateDate: match[11] || '', // L列是索引11
              closeDate: match[15] || '', // P列是索引15
              statusUpdate: match[13] || '', // N列是索引13
              closureStatus: match[18] || '', // S列是索引18
            };
            // 关闭搜索中提示
            loadingMessage.close();
            searchResults.value = `Found in sheet: ${sheet}`;
            ElMessage.success('Data Found!');
            return;
          }
        }
      }
    }
    // 关闭搜索中提示
    loadingMessage.close();
    searchResults.value = 'No records found.';
    ElMessage.error('No records found.');
  } catch (error) {
    // 关闭搜索中提示
    loadingMessage.close();
    searchResults.value = 'Reading data failed, please try again.';
    ElMessage.error('Reading data failed, please try again.');
    console.error(error);
  }
}

async function saveEntry() {
  const updates = {
    2: formData.value.tcfType,
    5: plmCode.value,
    8: formData.value.sampleReceivedDate,
    10: formData.value.reviewFromDate,
    11: formData.value.validateDate,
    13: formData.value.statusUpdate,
    15: formData.value.closeDate
  };

  await electronAPI.updatePartialColumns(
      activeSheetId.value,
      activeSheet.value,
      plmCode.value,
      updates,
      `${activeSheet.value}!A1:Z1000`
  );
}

async function handleEntry() {
  // 检查是否已输入并搜索过code
  if (!plmCode.value.trim() || !searchResults.value) {
    ElMessage.warning('Please search PLM Code first...');
    return;
  }

  try {
    const userSettings = await electronAPI.getUserSettings();

    // 用户信息检查
    if (!userSettings.email || !userSettings.site) {
      ElMessage.error('Please configure user email and site in Settings first!');
      // window.location.href = '/#/settings'; // 根据路由配置跳转
      return;
    }
    
    // 显示请稍后提示
    const loadingMessage = ElMessage({
      message: 'Updating Data, please wait...',
      duration: 0,
      type: 'info',
      showClose: false
    });

    // 调用原来的保存方法
    await saveEntry();

    // 构建监控数据
    const data: any[] = [
      {
        user_name: userSettings.email.split('@')[0],
        user_location: userSettings.site,
        rpa_id: "137",
        rpa_name: "Google Sheets Entry",
        rpa_version: "1.0.0",
        occurrence: format(new Date().toUTCString(), "EEE, dd MMM yyyy HH:mm:ss"),
        info: "Google Sheets数据更新",
        extra: plmCode.value
      }
    ];
    
    try {
      await electronAPI.sendMonitoringData(data);
      console.log('渲染进程：发送监控数据成功'); // 添加此行
    } catch (error) {
      console.error('渲染进程：发送监控数据失败:', error); // 添加此行
    }

    // 更新成功后显示成功提示
    ElMessage({
      message: 'Update Successfully!',
      type: 'success',
      duration: 0,
      showClose: true,
      onClose: () => {
        // 用户点击关闭后执行的操作
        console.log('关闭提示框...');
      }
    });

    // 关闭请稍后提示
    loadingMessage.close();
  } catch (error) {
    ElMessage.error('Update Failed!');
    console.error('Update Failed:', error);
  }
}

// 打开设置
function openSettings() {
  showSettings.value = true;
}

// 添加新的sheet
function addSheet() {
  sheetIds.value = [...sheetIds.value, '']; // 使用新数组确保响应式更新
}

// 删除sheet
function removeSheet(index: number) {
  sheetIds.value = sheetIds.value.filter((_, i) => i !== index); // 使用新数组确保响应式更新
}

// 保存设置
// 保存设置
function saveSettings() {
  try {
    // 过滤空值
    const validIds = sheetIds.value.filter(id => id.trim() !== '');

    // 保存到 localStorage
    localStorage.setItem('google-sheets-sheet-ids', JSON.stringify(validIds));

    ElMessage.success('Save Successfully!');
    closeSettings(); // 保存成功后关闭设置面板
  } catch (error) {
    console.error('Save failed:', error);
    ElMessage.error('Save failed!');
  }
}

// 关闭设置面板
function closeSettings() {
  showSettings.value = false;
}

</script>

<style lang='less' scoped>
/* back button */
button-back {
  align-items: center;
  background-color: transparent;
  color: #fff;
  cursor: pointer;
  display: flex;
  font-family: ui-sans-serif,system-ui,-apple-system,system-ui,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
  font-size: 1rem;
  font-weight: 700;
  line-height: 1.5;
  text-decoration: none;
  text-transform: uppercase;
  outline: 0;
  border: 0;
  padding: 1rem;
}

button-back:before {
  background-color: #fff;
  content: "";
  display: inline-block;
  height: 1px;
  margin-right: 10px;
  transition: all .42s cubic-bezier(.25,.8,.25,1);
  width: 0;
}

button-back:hover:before {
  background-color: #fff;
  width: 3rem;
}

/* From Uiverse.io by guilhermeyohan */
.entry-form {
  position: relative;
  margin-top: 20px;
  top: 50%;
  left: 50%;
  width: 750px;
  padding: 40px;
  transform: translate(-50%, 0%);
  background: rgba(24, 20, 20, 0.987);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0,0,0,.6);
  border-radius: 10px;
}

.form-columns {
  display: flex;
  justify-content: space-between;
}

.column {
  flex: 1;
  margin-right: 40px;
}

.column:last-child {
  margin-right: 0;
}

.entry-form .user-box {
  position: relative;
  margin-bottom: 20px; /* 增加行间距 */
}

.entry-form .user-box input {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
  color: #fff;
  margin-bottom: 30px;
  border: none;
  border-bottom: 1px solid #fff;
  outline: none;
  background: transparent;
}

.entry-form .user-box label {
  position: absolute;
  top: 0;
  left: 0;
  padding: 10px 0;
  font-size: 14px;
  color: #fff;
  pointer-events: none;
  transition: .5s;
}

.entry-form .user-box input:focus ~ label,
.entry-form .user-box input:valid ~ label {
  top: -20px;
  left: 0;
  color: #bdb8b8;
  font-size: 12px;
}

.entry-form form a {
  position: relative;
  display: inline-block;
  padding: 10px 20px;
  color: #ffffff;
  font-size: 16px;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  transition: .5s;
  margin-top: 0px;
  letter-spacing: 4px;
  align-self: flex-end; /* 使用Flexbox对齐按钮 */
}

.entry-form a:hover {
  background: #03f40f;
  color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 5px #03f40f,
  0 0 25px #03f40f,
  0 0 50px #03f40f,
  0 0 100px #03f40f;
}

.entry-form a span {
  position: absolute;
  display: block;
}

@keyframes btn-anim1 {
  0% {
    left: -100%;
  }

  50%,100% {
    left: 100%;
  }
}

.entry-form a span:nth-child(1) {
  bottom: 2px;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #03f40f);
  animation: btn-anim1 2s linear infinite;
}

/* From Uiverse.io by benjimich */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 35px;
  flex-shrink: 0; /* 确保按钮不会被压缩 */
  margin-bottom: 30px; /* 增加底部间距 */
  margin-right: 80px;

}

.input {
  max-width: 180px;
  height: 50%;
  outline: none;
  font-size: 14px;
  font-weight: 500;
  background-color: #53535f;
  caret-color: #f7f7f8;
  color: #fff;
  padding: 7px 10px;
  border: 2px solid transparent;
  border-top-left-radius: 7px;
  border-bottom-left-radius: 7px;
  margin-right: 1px;
  transition: all .2s ease;
}

.input:hover {
  border: 2px solid rgba(255, 255, 255, 0.16);
}

.input:focus {
  border: 2px solid #a970ff;
  background-color: #0e0e10;
}

.search__btn {
  border: none;
  cursor: pointer;
  background-color: rgba(42, 42, 45, 1);
  border-top-right-radius: 7px;
  border-bottom-right-radius: 7px;
  border-top-left-radius: 0; /* 确保左上角无圆角 */
  border-bottom-left-radius: 0; /* 确保左下角无圆角 */
  height: 100%;
  width: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4px; /* 增加内边距 */
  box-sizing: border-box; /* 确保内边距不影响按钮大小 */
}

.search__btn svg {
  width: 18px; /* 调整图标宽度 */
  height: 18px; /* 调整图标高度 */
  fill: #efeff1; /* 确保图标颜色与背景对比明显 */
}

.search__btn:hover {
  background-color: rgba(54, 54, 56, 1);
}

/* 设置按钮样式 */
.settings-btn {
  position: absolute;
  right: 40px;
  top: 40px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  outline: none;
}

.settings-btn svg {
  fill: #fff;
  transition: fill 0.3s;
}

.settings-btn:hover svg {
  fill: #000;
}

/* 设置面板样式 */
.settings-panel {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 470px;
  transform: translate(-50%, -50%);
  background: rgba(24, 20, 20, 0.987);
  padding: 20px;
  border-radius: 10px;
  z-index: 1000;
  border: 1px solid #a970ff;
}

.settings-panel button {
  background-color: #53535f;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin: 5px;
}

.settings-panel .add-sheet {
  background-color: #4285F4;
  color: #000;
}

.settings-panel button:hover {
  background-color: #357ABD;
  color: #000;
}

.sheet-item {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.sheet-item input {
  flex: 1;
  outline: none;
  font-size: 14px;
  font-weight: 500;
  caret-color: #f7f7f8;
  color: #fff;
  padding: 7px 10px;
  background: #53535f;
  border: 2px solid transparent;
  border-top-left-radius: 7px;
  border-bottom-left-radius: 7px;
  border-top-right-radius: 7px;
  border-bottom-right-radius: 7px;
  margin-right: 1px;
  transition: all .2s ease;
}

.sheet-item input:hover {
  border: 2px solid rgba(255, 255, 255, 0.16);
}

.sheet-item input:focus {
  border: 2px solid #a970ff;
  background-color: #0e0e10;
}

.red-text {
  color: #ff0000 !important;
  caret-color: #ff0000;
}
</style>